package com.health.institution.controller;

import java.util.List;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.health.common.annotation.Log;
import com.health.common.core.controller.BaseController;
import com.health.common.core.domain.AjaxResult;
import com.health.common.enums.BusinessType;
import com.health.institution.domain.MedicalHospital;
import com.health.institution.service.IMedicalHospitalService;
import com.health.common.utils.poi.ExcelUtil;
import com.health.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 机构管理Controller
 *
 * @author ruoyi
 * @date 2025-10-27
 */
@RestController
@RequestMapping("/institution/hospital")
public class MedicalHospitalController extends BaseController {
    @Autowired
    private IMedicalHospitalService medicalHospitalService;

    /**
     * 查询机构管理列表
     */
//    @PreAuthorize("@ss.hasPermi('institution:hospital:list')")
    @GetMapping("/list")
    public TableDataInfo list(MedicalHospital medicalHospital) {
        startPage();
        List<MedicalHospital> list = medicalHospitalService.selectMedicalHospitalList(medicalHospital);
        return getDataTable(list);
    }

    /**
     * 导出机构管理列表
     */
    @PreAuthorize("@ss.hasPermi('institution:hospital:export')")
    @Log(title = "机构管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MedicalHospital medicalHospital) {
        List<MedicalHospital> list = medicalHospitalService.selectMedicalHospitalList(medicalHospital);
        ExcelUtil<MedicalHospital> util = new ExcelUtil<MedicalHospital>(MedicalHospital.class);
        util.exportExcel(response, list, "机构管理数据");
    }

    /**
     * 获取机构管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('institution:hospital:query')")
    @GetMapping(value = "/{hospitalId}")
    public AjaxResult getInfo(@PathVariable("hospitalId") Long hospitalId) {
        return success(medicalHospitalService.selectMedicalHospitalByHospitalId(hospitalId));
    }

    /**
     * 获取机构管理详细信息（包含科室信息）
     */
    @PreAuthorize("@ss.hasPermi('institution:hospital:query')")
    @GetMapping(value = "/withDepartments/{hospitalId}")
    public AjaxResult getInfoWithDepartments(@PathVariable("hospitalId") Long hospitalId) {
        return success(medicalHospitalService.selectMedicalHospitalWithDepartments(hospitalId));
    }

    /**
     * 新增机构管理
     */
    @PreAuthorize("@ss.hasPermi('institution:hospital:add')")
    @Log(title = "机构管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MedicalHospital medicalHospital) {
        return toAjax(medicalHospitalService.insertMedicalHospital(medicalHospital));
    }

    /**
     * 新增机构管理（包含科室）
     */
    @PreAuthorize("@ss.hasPermi('institution:hospital:add')")
    @Log(title = "机构管理", businessType = BusinessType.INSERT)
    @PostMapping("/withDepartments")
    public AjaxResult addWithDepartments(@RequestBody MedicalHospital medicalHospital) {
        return toAjax(medicalHospitalService.insertMedicalHospitalWithDepartments(medicalHospital));
    }

    /**
     * 修改机构管理
     */
    @PreAuthorize("@ss.hasPermi('institution:hospital:edit')")
    @Log(title = "机构管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MedicalHospital medicalHospital) {
        return toAjax(medicalHospitalService.updateMedicalHospital(medicalHospital));
    }

    /**
     * 修改机构管理（包含科室）
     */
    @PreAuthorize("@ss.hasPermi('institution:hospital:edit')")
    @Log(title = "机构管理", businessType = BusinessType.UPDATE)
    @PutMapping("/withDepartments")
    public AjaxResult editWithDepartments(@RequestBody MedicalHospital medicalHospital) {
        return toAjax(medicalHospitalService.updateMedicalHospitalWithDepartments(medicalHospital));
    }

    /**
     * 删除机构管理
     */
    @PreAuthorize("@ss.hasPermi('institution:hospital:remove')")
    @Log(title = "机构管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{hospitalIds}")
    public AjaxResult remove(@PathVariable Long[] hospitalIds) {
        return toAjax(medicalHospitalService.deleteMedicalHospitalByHospitalIds(hospitalIds));
    }

    /**
     * 上传机构Logo
     */
    @PreAuthorize("@ss.hasPermi('institution:hospital:edit')")
    @Log(title = "机构管理", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadLogo")
    public AjaxResult uploadLogo(@RequestParam("file") MultipartFile file, @RequestParam("hospitalId") Long hospitalId) {
        try {
            // 添加详细的文件验证
            if (file == null || file.isEmpty()) {
                return error("上传文件不能为空");
            }
            // 检查文件大小
            if (file.getSize() == 0) {
                return error("文件大小为0");
            }
            // 检查文件名，如果为空则记录日志
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.trim().isEmpty()) {
                // 记录警告日志但不阻止上传，因为MinIOUtils可能能处理
                logger.warn("上传的文件名为空，hospitalId: {}", hospitalId);
            }
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return error("只能上传图片文件");
            }
            // 记录上传信息用于调试
            logger.info("上传Logo - hospitalId: {}, 文件名: {}, 大小: {}, 类型: {}",
                    hospitalId,
                    originalFilename != null ? originalFilename : "null",
                    file.getSize(),
                    contentType);
            String logoUrl = medicalHospitalService.uploadLogo(file, hospitalId);
            return success(logoUrl);
        } catch (Exception e) {
            logger.error("机构Logo上传失败, hospitalId: {}", hospitalId, e);
            return error("机构Logo上传失败: " + e.getMessage());
        }
    }

}